package com.dxl.dao.account;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.dxl.common.enums.State;
import com.dxl.common.model.Page;
import com.dxl.common.utils.MD5;
import com.dxl.common.utils.SqlBuilder;
import com.dxl.common.utils.Utils;
import com.dxl.dao.common.BaseDao;
import com.dxl.entity.account.Account;

/**
 * 账户管理DAO
 * @author 邓小林
 */
@Repository
public class AccountDao extends BaseDao {
	private static final Logger LOG = Logger.getLogger(AccountDao.class);
	
	public Page<Account> list(String keyword, Integer state, Integer pageNo, Integer pageSize) {
		SqlBuilder sb = new SqlBuilder("select * from account where 1 = 1");
		if (Utils.isNotBlank(keyword)) {
			keyword = keyword.trim();
			sb.appendStatement(" and (");
			sb.appendStatement(" name like ").appendParamValue("%" + keyword + "%");
			sb.appendStatement(" or mobile like ").appendParamValue("%" + keyword + "%");
			sb.appendStatement(" or email like ").appendParamValue("%" + keyword + "%");
			sb.appendStatement(" or account like ").appendParamValue("%" + keyword + "%");
			sb.appendStatement(")");
		}
		if (Utils.isNotNull(state)) {
			sb.appendStatement(" and state = ").appendParamValue(state);
		}
		sb.appendStatement(" order by created_time desc");
		return this.list(Account.class, sb.toStatement(), sb.toParams(), pageNo, pageSize);
	}
	
	public Account list(String account, String password, State state) {
		SqlBuilder sb = new SqlBuilder("select * from account where 1 = 1");
		account = account.trim();
		sb.appendStatement(" and (");
		sb.appendStatement(" mobile = ").appendParamValue(account);
		sb.appendStatement(" or email = ").appendParamValue(account);
		sb.appendStatement(" or account = ").appendParamValue(account);
		sb.appendStatement(")");
		sb.appendStatement(" and password = ").appendParamValue(MD5.crypt(password));
		if (Utils.isNotNull(state)) {
			sb.appendStatement(" and state = ").appendParamValue(state.getState());
		}
		sb.appendStatement(" order by created_time desc");
		List<Account> accounts = this.list(Account.class, sb.toStatement(), sb.toParams());
		int size = accounts.size();
		if (size > 1) {
			LOG.error("存在重复账号记录，请检查数据，账号：" + account);
		}
		return Utils.isEmpty(accounts) ? null : accounts.get(0);
	}
	
	public int deleteAccountRole(String[] roleIds) {
		if (Utils.isEmpty(roleIds)) {
			return 0;
		}
		SqlBuilder sb = new SqlBuilder("delete from account_role where role_id in ").appendParamValues(roleIds);
		return this.del(sb.toStatement(), sb.toParams());
	}
}
